package cz.none.bezbarier.web.tl.processor;

import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.ProcessorResult;
import org.thymeleaf.processor.attr.AbstractAttrProcessor;
import org.thymeleaf.standard.expression.StandardExpressionProcessor;

public abstract class AInputTextProcessor extends AbstractAttrProcessor {

	public AInputTextProcessor(String attributeName) {
		super(attributeName);
	}

	@Override
	protected ProcessorResult processAttribute(Arguments arguments, Element element, String attributeName) {
		String value = element.getAttributeValue(attributeName);
		String[] values = value.split(";");
		if (values.length < 2) {
			throw new RuntimeException();
		}

		String field = values[1];
		String placeholder = (String) StandardExpressionProcessor.processExpression(arguments, values[0]);
		String errorCheck = "class=${#fields.hasErrors('" + field + "')}? ' error'";

		Element input = new Element("input");
		input.setAttribute("type", getInputType());
		input.setAttribute("class", "input-block-level");
		input.setAttribute("placeholder", placeholder);
		input.setAttribute("name", field);
		input.setAttribute("id", field);
		input.setAttribute("th:field", "*{" + field + "}");

		element.addChild(input);
		element.setAttribute("class", "control-group");
		element.setAttribute("th:attrappend", errorCheck);

		element.removeAttribute(attributeName);

		element.setRecomputeProcessorsImmediately(true);

		return ProcessorResult.OK;
	}

	protected abstract String getInputType();

}
